import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from 'element-plus'
import {
  deliveryOrderListApi,
  deliveryOrderStoreApi,
  deliveryOrderUpdateApi,
  deliveryOrderDeleteApi,
  deliveryOrderShowApi,
  deliveryOrderUpdateStatusApi
} from "@/api/purchaseOrderApi";
import { companySelectApi } from "@/api/quotedPriceApi";
import { customerSelectApi } from "@/api/customerApi";

export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 20,
    orderNo: null,
    customerId: null,
    orderType: null,
    status: null,
    orderRangeDate: null,
    companyId: null,
    keyword: null,
    sortType: null,
    sortOrder: null,
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const higherDeptOptions = ref();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true,
    pageSizes: [10,20,50,100]
  });
  const columns: TableColumnList = [
    { type: "expand", slot: "expand"},
    { type: "selection", width: 50, selectable: ({ status }) => {
     return status === 2 ? true : false;
    }},
    // { label: "ID", prop: "deliveryOrderId", width: 70, sortable: true},
    { label: "出库单号", prop: "orderNo", minWidth: 150, formatter:(row: any)=> {
	  	return row.orderNo || '--'
	  }},
    { label: "公司", prop: "company", minWidth: 150, formatter:(row: any)=> {
    	return row.company?.companyName || '--'
    }},

    { label: "出库单日期", prop: "orderDate", minWidth: 120, sortable: true},
    { label: "单据类型", prop: "orderTypeName", minWidth: 100},
    { label: "单据状态", prop: "statusName", slot: "statusName", minWidth: 100},
    { label: "客户", prop: "customer", minWidth: 100, formatter:(row: any)=> {
    	return row.customer?.name || '--'
    }},
    // { label: "主管", prop: "supervisor", minWidth: 90, formatter:(row: any)=> {
    // 	return row.supervisor || '--'
    // }},
    // { label: "出单员", prop: "keyboarder", minWidth: 90, formatter:(row: any)=> {
    // 	return row.keyboarder || '--'
    // }},
    // { label: "经办人", prop: "transactor", minWidth: 90, formatter:(row: any)=> {
    // 	return row.transactor || '--'
    // }},
    { label: "备注", prop: "remarks", minWidth: 120, formatter:(row: any)=> {
    	return row.remarks || '--'
    }},
    { label: "创建时间", prop: "createdAt", minWidth: 160, sortable: true},
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 180
    }
  ];
  const expandColumns: TableColumnList = [
    { label: "产品名称", prop: "productName", minWidth: 150, formatter:(row: any)=> {
    	return row.product?.productName || '--'
    }},
    { label: "产品编号", prop: "productNo", minWidth: 150, sortable: true, formatter:(row: any)=> {
    	return row.product?.productNo || '--'
    }},
    { label: "规格", prop: "productSpec", minWidth: 150, formatter:(row: any)=> {
    	return row.product?.productSpec || '--'
    }},
    { label: "单位", prop: "productUnit", width: 80, formatter:(row: any)=> {
    	return row.product?.productUnit || '--'
    }},
    { label: "数量", prop: "number", width: 100, formatter:(row: any)=> {
    	return row.number*1 || '--'
    }},
    { label: "产品单价", prop: "price", minWidth: 100, formatter:(row: any)=> {
    	return row.price*1 || '--'
    }},
    { label: "总金额", prop: "amount", minWidth: 90, formatter:(row: any)=> {
    	return row.amount*1 || '--'
    }},
    { label: "分类", prop: "category", minWidth: 100, formatter:(row: any)=> {
    	return row.product?.category?.name || '--'
    }},
    { label: "项目", prop: "projectName", minWidth: 150, formatter:(row: any)=> {
    	return row.product?.project.projectName || '--'
    }},
    { label: "备注", prop: "remarks", minWidth: 120, formatter:(row: any)=> {
    	return row.product?.remarks || '--'
    }},
    { label: "仓库", prop: "store", minWidth: 150, formatter:(row: any)=> {
    	return row.product?.store.name || '--'
    }},
  ];
  function handleSizeChange(val: number) {
    form.page = 1;
    form.perPage = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    let params = {
      orderNo: form.orderNo,
      orderStartDate: form.orderRangeDate ? form.orderRangeDate[0]:null,
      orderEndDate: form.orderRangeDate ? form.orderRangeDate[1]:null,
      orderType: form.orderType,
      companyId: form.companyId,
      customerId: form.customerId,
      keyword: form.keyword,
      status: form.status,
      page: form.page,
      perPage: form.perPage,
      sortType: form.sortType,
      sortOrder: form.sortOrder,
    }
    const res: any = await deliveryOrderListApi(cleanEmptyData(params));
    dataList.value = res?.result.list;
    pagination.total = res?.result.total;
    pagination.pageSize = res?.result.perPage*1;
    pagination.currentPage = res?.result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.page = 1;
    form.orderNo = null;
    form.customerId = null;
    form.orderType = null;
    form.status = null;
    form.orderRangeDate = null;
    form.keyword = null;
    form.companyId = null;
    form.sortType = null;
    form.sortOrder = null;
    formEl.resetFields();
    onSearch();
  };
  // 删除参数为空的键值
  function cleanEmptyData(obj: object) {
    Object.keys(obj).forEach(key => {
      if (obj[key] === null || obj[key] === '') {
        delete obj[key];
      }
    });
    return obj
  }
  async function openDialog(title = "创建订单", row?: FormItemProps) {
    if(title === '执行') {
      ElMessageBox.confirm("确定继续此操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
        deliveryOrderUpdateStatusApi({
          deliveryOrderId: row.deliveryOrderId,
          status: 2, // 单据状态 [1-待执行、2-已执行、3-XXX]
        }).then((res: any) => {
          if (res.code == 200) {
            onSearch();
          } else {
            message(res.message, {
              type: "error"
            });
          }
        });
      })
      return
    }
	  let formInline ={
      title: title,
      deliveryOrderId: row?.deliveryOrderId ?? null,
      detaileInfo: null,
      updateToStore: 0,
      productList: [{productName: null,productNo: null, number: null,remarks: '', amount: ''}],
      projectSelect: null,
      orderNo: null,
      orderDate: null,
      companyId: null,
      orderType: null,
      customerId: null,
      keyboarder: null,
      supervisor: null,
      transactor: null,
      remarks: null,
      supplierList: null,
      userList: null,
    }

    if(title === '订单详情' || title === '编辑订单') {
      const res: any = await deliveryOrderShowApi({
        deliveryOrderId: row.deliveryOrderId
      });
      formInline.detaileInfo = res?.result;
      formInline.orderNo = res?.result?.orderNo;
      formInline.orderDate = res?.result?.orderDate;
      formInline.companyId = res?.result?.companyId;
      formInline.orderType = res?.result?.orderType;
      formInline.customerId = res?.result?.customerId;
      formInline.keyboarder = res?.result?.keyboarder;
      formInline.supervisor = res?.result?.supervisor;
      formInline.transactor = res?.result?.transactor;
      formInline.remarks = res?.result?.remarks;
      formInline.updateToStore = res?.result?.updateToStore ?? 0;
      // let p = [];
      for (let item of res?.result?.orderProducts) {
        // p.push({
        //   productName: item.product?.productName,productNo: item.product?.productNo, number: item.number,remarks: item.remarks
        // })
        item.productNo = item?.product?.productNo;
        item.productInfo = item.product;
      }
      formInline.productList = res?.result?.orderProducts;
    }
    addDialog({
      title: `${title}`,
      props: {
        formInline: formInline
      },
      top: '2%',
      width: "80%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      hideFooter: title === '订单详情' ? true : false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            if(title === '创建订单' || title === '编辑订单') {
              let productList = []
              for (let item of curData.productList) {
                if(!item.productNo) {
                  message('请输入商品编号', {
                    type: "warning"
                  });
                  return
                }
                if(!item.number) {
                  message('请输入数量', {
                    type: "warning"
                  });
                  return
                }
                // if(!item.remarks) {
                //   message('请输入备注', {
                //     type: "warning"
                //   });
                //   return
                // }
                item.number = (item.number*1).toFixed(4);
                productList.push({
                  productNo: item.productNo,
                  number: item.number,
                  remarks: item.remarks || ''
                })
              }
              let params = {
                deliveryOrderId: curData.deliveryOrderId,
                orderNo: curData.orderNo,
                orderDate: curData.orderDate,
                companyId: curData.companyId,
                orderType: curData.orderType,
                customerId: curData.customerId,
                keyboarder: curData.keyboarder.toString(),
                supervisor: curData.supervisor.toString(),
                transactor: curData.transactor.toString(),
                remarks: curData.remarks,
                productList: curData.productList,
                updateToStore: curData.updateToStore,
              }
              console.log(params)
              if(title === '创建订单') {
                deliveryOrderStoreApi(cleanEmptyData(params)).then((res: any) => {
                  if(res?.code === 200) {
                    chores();
                  }
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
              } else {
                params.productList = productList
                deliveryOrderUpdateApi(cleanEmptyData(params)).then((res: any) => {
                  if(res?.code === 200) {
                    chores();
                  }
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
              }

            }
          }
        });
      }
    });
  }
  const companySelect = ref()
  const customerSelect = ref()
  onMounted(async () => {
    onSearch();
    // 获取公司
    const company: any = await companySelectApi();
    companySelect.value = company?.result;

    // 获取客户
    const customer: any = await customerSelectApi();
    customerSelect.value = customer?.result;
  });

  function handleDelete(row: any) {
    ElMessageBox.confirm("确定继续此操作?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(() => {
      deliveryOrderDeleteApi({
        deliveryOrderId: row.deliveryOrderId
      }).then((res: any) => {
        if (res.code == 200) {
          message(`删除成功`, { type: "success" });
          onSearch();
        } else {
          message(res.message, {
            type: "error"
          });
        }
      });
    })

  }
  function sortChange (column, prop, order) {
    form.sortOrder = "";
    if (column.order == "descending") {
      form.sortOrder = "desc";
      if (column.prop === "deliveryOrderId") {
        form.sortType = "id";
      } else if(column.prop === 'orderDate') {
        form.sortType = "order_date";
      } else if(column.prop === 'createdAt') {
        form.sortType = "created_at";
      } else {
        form.sortType = column.prop;
      }
    } else if (column.order == "ascending") {
      form.sortOrder = "asc";
      if (column.prop === "deliveryOrderId") {
        form.sortType = "id";
      } else if(column.prop === 'orderDate') {
        form.sortType = "order_date";
      } else if(column.prop === 'createdAt') {
        form.sortType = "created_at";
      } else {
        form.sortType = column.prop;
      }
    } else {
      form.sortOrder = "";
      form.sortType = "";
    }
    onSearch()
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
    companySelect,
    customerSelect,
    sortChange,
    expandColumns
  };
}
